package org.springframework.beans.util;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;

public class ClassUtil {

    public static ClassLoader getDefaultClassLoader() {
        ClassLoader classLoader = null;
        try {
            classLoader = Thread.currentThread().getContextClassLoader();
        } catch (Exception e) {

        }
        if (classLoader == null) {
            classLoader = ClassUtil.class.getClassLoader();
        }
        return classLoader;
    }

    public static Field getFiled(Object obj, String name) {
        Class clazz = obj instanceof Class ? (Class) obj : obj.getClass();
        Field[] fields = getFileds(clazz);
        for (Field field : fields) {
            if (field.getName().equals(name)) {
                return field;
            }
        }
        return null;
    }

    private static Field[] getFileds(Class<?> clazz) {
        Field[] fields = null;
        Class<?> clazzToUse = clazz;
        while (clazzToUse != null) {
            Field[] declaredFields = clazzToUse.getDeclaredFields();
            fields = append(fields, declaredFields);
            clazzToUse = clazzToUse.getSuperclass();
        }
        return fields;
    }

    public static boolean isCglibProxyClass(Class<?> clazz) {
        return (clazz != null && isCglibProxyClassName(clazz.getName()));
    }

    public static boolean isCglibProxyClassName(String className) {
        return (Misc.isNotEmpty(className) && className.contains("$$"));
    }


    private static <T> T[] append(T[] target, T[] element) {
        if (target == null) {
            return element;
        }
        if (element == null) {
            return target;
        }

        int len = target.length + element.length;

        T[] result = (T[]) Array.newInstance(target.getClass().getComponentType(), len);

        System.arraycopy(target, 0, result, 0, target.length);
        System.arraycopy(element, 0, result, target.length, element.length);
        return result;
    }
}
